﻿using Manon.Autofac;
using Manon.ConfigCenter.Web.ApplicationCore.Interfaces;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Manon.ConfigCenter.Web.Common
{

    /// <summary>
    /// Baseic 认证
    /// </summary>
    public class BasicAuthAttribute : Attribute, IAuthorizationFilter
    {


        void IAuthorizationFilter.OnAuthorization(AuthorizationFilterContext context)
        {
            long timestamp = DateTimeHelper.GetUnixTimestamp();
            string reqUrl = context.HttpContext.Request.Path;
            string[] patharray = reqUrl.Split('/');

            string envCode = patharray[patharray.Length - 2];
            string projectCode = patharray[patharray.Length - 1];
            string authCode = context.HttpContext.Request.Headers["Authorization"].ToString();
            if (string.IsNullOrEmpty(authCode))
            {
                //context.Result = new JsonResult(new
                //{
                //    StatusCode = 401,
                //    Exception = "",
                //    Message = "无权访问",
                //    Path = reqUrl,
                //    Timestamp = timestamp
                //});
                //return;
                AuthenticateResult.Fail("无权访问");
                return;
            }
            var projectService = Resolver.Resolve<IProjectService>();
            var SecretData = projectService.GetProjectEnvSecret(projectCode, envCode).GetAwaiter().GetResult();
            string secret = System.Convert.ToBase64String(Encoding.UTF8.GetBytes($"{SecretData.ClientId}:{SecretData.SecretKey}"));
             
            string dbAuthCode = $"Basic {secret}";
            if (!string.Equals(dbAuthCode, authCode, StringComparison.CurrentCultureIgnoreCase))
            {
                //context.Result = new JsonResult(new
                //{
                //    StatusCode = 401,
                //    Exception = "",
                //    Message = "无权访问",
                //    Path = reqUrl,
                //    Timestamp = timestamp
                //});
                //return;
                AuthenticateResult.Fail("无权访问");
                return;
            }
        }
    }



}

